import AsyncStorage from '@react-native-async-storage/async-storage';

// 缓存类型枚举
export enum CacheType {
  PERMANENT = 'PERMANENT',
  TEMPORARY = 'TEMPORARY',
}

class CacheManager {
  // 存储缓存
  static async setCache(
    key: string,
    value: any,
    type: CacheType = CacheType.TEMPORARY,
    expiryDays: number = 7 // 默认7天过期
  ): Promise<void> {
    try {
      const data = {
        value,
        type,
        createdAt: new Date().getTime(),
        expiryAt: type === CacheType.PERMANENT ? null : new Date().getTime() + expiryDays * 24 * 60 * 60 * 1000,
      };
      await AsyncStorage.setItem(`cache_${key}`, JSON.stringify(data));
    } catch (error) {
      console.error('CacheManager: Error setting cache:', error);
    }
  }

  // 获取缓存
  static async getCache(key: string): Promise<any | null> {
    try {
      const data = await AsyncStorage.getItem(`cache_${key}`);
      if (!data) return null;

      const parsedData = JSON.parse(data);

      // 检查是否过期
      if (parsedData.type !== CacheType.PERMANENT && parsedData.expiryAt && parsedData.expiryAt < new Date().getTime()) {
        // 过期则删除并返回null
        await this.deleteCache(key);
        return null;
      }

      return parsedData.value;
    } catch (error) {
      console.error('CacheManager: Error getting cache:', error);
      return null;
    }
  }

  // 删除缓存
  static async deleteCache(key: string): Promise<void> {
    try {
      await AsyncStorage.removeItem(`cache_${key}`);
    } catch (error) {
      console.error('CacheManager: Error deleting cache:', error);
    }
  }

  // 清除所有临时缓存
  static async clearTemporaryCache(): Promise<void> {
    try {
      const keys = await AsyncStorage.getAllKeys();
      const cacheKeys = keys.filter(key => key.startsWith('cache_'));

      for (const key of cacheKeys) {
        const data = await AsyncStorage.getItem(key);
        if (data) {
          const parsedData = JSON.parse(data);
          if (parsedData.type !== CacheType.PERMANENT && parsedData.expiryAt && parsedData.expiryAt < new Date().getTime()) {
            await AsyncStorage.removeItem(key);
          }
        }
      }
    } catch (error) {
      console.error('CacheManager: Error clearing temporary cache:', error);
    }
  }

  // 清除所有缓存
  static async clearAllCache(): Promise<void> {
    try {
      const keys = await AsyncStorage.getAllKeys();
      const cacheKeys = keys.filter(key => key.startsWith('cache_'));
      await AsyncStorage.multiRemove(cacheKeys);
    } catch (error) {
      console.error('CacheManager: Error clearing all cache:', error);
    }
  }

  // 验证缓存是否过期
  static async isCacheExpired(key: string): Promise<boolean> {
    try {
      const data = await AsyncStorage.getItem(`cache_${key}`);
      if (!data) return true;

      const parsedData = JSON.parse(data);
      if (parsedData.type === CacheType.PERMANENT) return false;

      return !!(parsedData.expiryAt && parsedData.expiryAt < new Date().getTime());
    } catch (error) {
      console.error('CacheManager: Error checking cache expiry:', error);
      return true;
    }
  }
}

export default CacheManager;